package com.yx.common.log.aspect;


import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.yx.common.core.domain.SysOperLog;
import com.yx.common.core.domain.UserAssociatedVO;
import com.yx.common.core.utils.IpUtils;
import com.yx.common.core.utils.ServletUtils;
import com.yx.common.core.utils.StringUtils;
import com.yx.common.log.annotation.Log;
import com.yx.common.log.enums.BusinessStatus;
import com.yx.common.log.service.LogService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.NamedThreadLocal;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Stream;

import static com.yx.common.core.constant.Constants.LOGIN_USER_INFO;


/**
 * 操作日志记录处理
 *
 * @author sgcc
 */
@Aspect
@Component
public class LogAspect {
    private static final Logger log = LoggerFactory.getLogger(LogAspect.class);

    private static final String[] EXCLUDE_PROPERTIES = {"password", "oldPassword", "newPassword", "confirmPassword"};
    private static final NamedThreadLocal<Long> TIME_THREAD_LOCAL = new NamedThreadLocal<>("Cost Time");

    @Value("${log.msg.length:2000}")
    private Integer MSG_LENGTH;

    @Autowired
    private LogService logService;

    @Before("@annotation(controllerLog)")
    public void before(Log controllerLog) {
        TIME_THREAD_LOCAL.set(System.currentTimeMillis());
    }

    @AfterReturning(pointcut = "@annotation(controllerLog)", returning = "jsonResult")
    public void afterReturning(JoinPoint joinPoint, Log controllerLog, Object jsonResult) {
        handleLog(joinPoint, controllerLog, null, jsonResult);
    }

    @AfterThrowing(pointcut = "@annotation(controllerLog)", throwing = "e")
    public void afterThrowing(JoinPoint joinPoint, Log controllerLog, Exception e) {
        handleLog(joinPoint, controllerLog, e, null);
    }

    private void handleLog(final JoinPoint joinPoint, Log controllerLog, final Exception e, Object jsonResult) {
        try {
            SysOperLog operLog = new SysOperLog();
            operLog.setStatus(BusinessStatus.SUCCESS.ordinal());
            operLog.setOperIp(IpUtils.getIpAddr());
            operLog.setOperUrl(StringUtils.substring(Objects.requireNonNull(ServletUtils.getRequest()).getRequestURI(), 0, 255));

            UserAssociatedVO userAssociatedVO = (UserAssociatedVO) StpUtil.getSession().get(LOGIN_USER_INFO);
            String username = userAssociatedVO.getUserName();
            if (StringUtils.isNotBlank(username)) {
                operLog.setOperName(username);
            }

            if (e != null) {
                operLog.setStatus(BusinessStatus.FAIL.ordinal());
                operLog.setErrorMsg(StringUtils.substring(e.getMessage(), 0, MSG_LENGTH));
            }

            operLog.setMethod(getTargetMethodName(joinPoint));
            operLog.setRequestMethod(ServletUtils.getRequest().getMethod());
            getControllerMethodDescription(joinPoint, controllerLog, operLog, jsonResult);
            operLog.setCostTime(System.currentTimeMillis() - TIME_THREAD_LOCAL.get());
            //operLog.setDeptName(userAssociatedVO.getDeptName());
            logService.saveSysLog(operLog);
        } catch (Exception exp) {
            exp.printStackTrace();
            log.error("异常信息:{}", exp.getMessage());
        } finally {
            TIME_THREAD_LOCAL.remove();
        }
    }

    private String getTargetMethodName(JoinPoint joinPoint) {
        return joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()";
    }

    public void getControllerMethodDescription(JoinPoint joinPoint, Log log, SysOperLog operLog, Object jsonResult) {
        // 设置action动作
        operLog.setBusinessType(log.businessType().ordinal());
        // 设置标题
        operLog.setTitle(log.title());
        // 设置操作人类别
        operLog.setOperatorType(log.operatorType().ordinal());
        // 是否需要保存request，参数和值
        if (log.isSaveRequestData())
        {
            // 获取参数的信息，传入到数据库中。
            setRequestValue(joinPoint, operLog, log.excludeParamNames());
        }
        // 是否需要保存response，参数和值
        if (log.isSaveResponseData() && StringUtils.isNotNull(jsonResult))
        {
            String result =  toJsonStrWithFilter(jsonResult,EXCLUDE_PROPERTIES);
            operLog.setJsonResult(StringUtils.substring(result, 0, MSG_LENGTH));
        }
    }



    private void setRequestValue(JoinPoint joinPoint, SysOperLog operLog, String[] excludeParamNames) {
        String requestMethod = operLog.getRequestMethod();
        Map<?, ?> paramsMap = ServletUtils.getParamMap(ServletUtils.getRequest());
        if (StringUtils.isEmpty(paramsMap)
                && (HttpMethod.PUT.name().equals(requestMethod)
                || HttpMethod.POST.name().equals(requestMethod))) {
            String params = argsArrayToString(joinPoint.getArgs());
            operLog.setOperParam(StringUtils.substring(params, 0, MSG_LENGTH));
        } else {
            //需要排除的字段名
            String[] mergedArray = Stream.of(EXCLUDE_PROPERTIES, excludeParamNames)
                    .flatMap(Stream::of)
                    .toArray(String[]::new);
            String result =  toJsonStrWithFilter(paramsMap,mergedArray);
            operLog.setOperParam(StringUtils.substring(result, 0, MSG_LENGTH));
        }
    }


    public static String toJsonStrWithFilter(Object object, String... ignoreProperties) {
        // 将对象转换为 JSONObject
        JSONObject jsonObject = JSONUtil.parseObj(object);
        // 转换 ignoreProperties 为 Set 方便查找
        Set<String> ignoreSet = new HashSet<>(Arrays.asList(ignoreProperties));
        // 移除指定的属性
        for (String prop : ignoreSet) {
            jsonObject.remove(prop);
        }
        return jsonObject.toString();
    }

    private String argsArrayToString(Object[] paramsArray) {
        StringBuilder params = new StringBuilder();
        if (paramsArray != null) {
            for (Object o : paramsArray) {
                if (StringUtils.isNotNull(o) && !isFilterObject(o)) {
                    String jsonObj =  toJsonStrWithFilter(o,EXCLUDE_PROPERTIES);
                    params.append(jsonObj).append(" ");
                }
            }
        }
        return params.toString().trim();
    }

    private boolean isFilterObject(final Object o) {
        Class<?> clazz = o.getClass();
        if (clazz.isArray()) {
            return clazz.getComponentType().isAssignableFrom(MultipartFile.class);
        } else if (Collection.class.isAssignableFrom(clazz)) {
            Collection<?> collection = (Collection<?>) o;
            return collection.stream().anyMatch(value -> value instanceof MultipartFile);
        } else if (Map.class.isAssignableFrom(clazz)) {
            Map<?, ?> map = (Map<?, ?>) o;
            return map.values().stream().anyMatch(value -> value instanceof MultipartFile);
        }
        return o instanceof MultipartFile || o instanceof HttpServletRequest || o instanceof HttpServletResponse || o instanceof BindingResult;
    }
}